package arithmetic.blockingqueue;

import java.util.LinkedList;

/**
 * 自定义用链表实现一个阻塞队列例子
 * @author lidd
 *
 */
public class MyBlockingQueue {

	private int capacity;
	private LinkedList<Integer> queue = new LinkedList<Integer>();

	public MyBlockingQueue() {
		this.capacity = Integer.MAX_VALUE;
	}

	public MyBlockingQueue(int capacity) {
		this.capacity = capacity;
	}

	public synchronized void put(Integer data) throws InterruptedException {
		while(this.capacity == this.queue.size()) {
			wait();
		}
		if(this.queue.size() == 0) {
			notifyAll();
		}
		this.queue.addFirst(data);
	}

	public synchronized Integer take() throws InterruptedException {
		while(this.queue.size() == 0) {
			this.wait();
		}
		if(this.capacity == this.queue.size()) {
			this.notifyAll();
		}
		return this.queue.removeLast();
	}

	public int size() {
		return this.queue.size();
	}
}
